package view;

import com.alibaba.fastjson.JSON;
import model.ViewForExpress;
import model.ViewForRelation;
import pond.common.STRING;
import pond.web.Render;
import pond.web.Router;
import service.DataBaseService;
import service.RelationService;

import java.util.List;
import java.util.Map;

/**
 * Created by sky_wang on 2017/7/20.
 */
public class Relation extends Router {
    private DataBaseService dataBaseService;
    public Relation (DataBaseService dataBaseService){
        this.dataBaseService = dataBaseService;
    }
    {
        get("/:id", (req, resp) -> {
            String id = req.paramNonBlank("id", "id不能为空");
            RelationService relationService = new RelationService(dataBaseService.getDB());
            ViewForRelation vfr = relationService.get(id);
            if (vfr !=null)
            {
                resp.render(Render.json(vfr));
            }
            else
            {
                resp.send(403, id + " not existed ");
            }
        });


        put("/:id", (req, resp) -> {
            String id = req.paramNonBlank("id", "id不能为空");
            String data = req.paramNonBlank("data", "data不能为空");
            RelationService relationService = new RelationService(dataBaseService.getDB());
            if (! relationService.isExist(id)) {
                resp.send(403, id + "did not exist");
            }
            Map<String, Object> map = (Map<String, Object>)JSON.parse(data);
            ViewForRelation vfr = new ViewForRelation() {
                {
                    set("vid", map.get("vid"));
                    set("relation_data_default", map.get("relation_data_default"));
                    set("relation_data_config", map.get("relation_data_config"));
                }
            };
            if (relationService.update(vfr)) {
                /* 更新内存数据 */
                if (STRING.notBlank(vfr.get("relation_data_config").toString()))
                {
                    dataBaseService.updateRelationGroupMap(vfr.get("relation_data_config").toString());
                }
                resp.send(200, "ok");
            } else {
                resp.send(403, id + "add failed ");
            }
        });
    }
}
